package com.mediacloud.app.newsmodule.fragment

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.luck.picture.lib.tools.DoubleUtils
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.MagazineProgramActivity
import com.mediacloud.app.newsmodule.adaptor.MagazineReviewListAdapter
import com.mediacloud.app.newsmodule.adaptor.MagazineReviewTopAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.model.MagazineReviewBean
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.appcloud.project.gxapp.model.utils.FAST
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.dialog_review_layout.view.*
import kotlinx.android.synthetic.main.fragment_magezine_review_layout.*
import org.json.JSONObject

/**
 * 杂志往期回顾
 */
class MagazineReviewFragment : BaseFragment() {

    val magazineId by lazy {
        arguments?.getString("magazineID", "")
    }
    val topList: ArrayList<String> by lazy {
        arrayListOf()
    }
    val allList: ArrayList<String> by lazy {
        arrayListOf()
    }


    var year: String = "2023"
    var preLoadKit: ListPreLoadKit<MutableList<MultiItemEntity>>? = null
    var adapter: MagazineReviewListAdapter? = null
    var topAdapter: MagazineReviewTopAdapter? = null

    companion object {

        fun getInstance(magazineId: String?): MagazineReviewFragment {
            val fragment = MagazineReviewFragment()
            val bundle = Bundle()
            bundle.putString("magazineID", magazineId)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.fragment_magezine_review_layout
    }

    override fun initView() {

        showStateView(BaseBackActivity.TYPE_LOADING, false)
        reviewTopList.layoutManager = GridLayoutManager(context, 4)
        topAdapter = MagazineReviewTopAdapter(context, topList)
        reviewTopList.adapter = topAdapter
        topAdapter!!.setCheckItemClickListener { position ->
            year = topList[position]
            getReviewList()
        }
        reviewList.layoutManager = GridLayoutManager(context, 3)
        adapter = MagazineReviewListAdapter()
        reviewList.adapter = adapter
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            if(DoubleUtils.isFastDoubleClick()){
                return@setOnItemChildClickListener
            }
            val item = adapter.getItem(position)
            if (item is MagazineReviewBean) {
                if (TextUtils.isEmpty( item.id.toString())) {
                  //  ToastUtil.show(context, "id参数为空")
                    return@setOnItemChildClickListener
                }
                val intent = Intent(requireContext(), MagazineProgramActivity::class.java)
                intent.putExtra("magazineID", item.id.toString())
                requireContext().startActivity(intent)
                if (activity is MagazineProgramActivity) {
                    (activity as MagazineProgramActivity).finish()
                }
            }

        }

        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        loadingImage.setOnClickListener {
            if (currentState != BaseBackActivity.TYPE_LOADING) {
                showStateView(BaseBackActivity.TYPE_LOADING, false)
                getReviewYearList()
            }
        }
        btnMore.setOnClickListener {
            allReviewDialog()
        }
        getReviewYearList()
    }


    private fun getReviewYearList() {

        SpiderCmsApi.getSpiderCmsApiJson(context)
            .getMagazineReviewList(if (!TextUtils.isEmpty(magazineId)) magazineId!!.toLong() else 0L)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: JSONObject) {
                    t.let {
                        val data = it.optJSONArray("data")
                        val state = it.optInt("state")
                        if (state == 200) {
                            val taskList =
                                FAST.parseArray(data.toString(), String::class.java) as ArrayList
                            if (taskList.size > 0) {
                                closeStateView()
                                if (taskList.size >= 4) {
                                    for (i in 0..3) {
                                        topList.add(taskList[i])
                                    }
                                } else {
                                    topList.addAll(taskList)
                                }
                                openMore.visibility = View.VISIBLE
                                year = topList[0]
                                allList.addAll(taskList)
                                topAdapter?.notifyDataSetChanged()
                            } else {
                                showStateView(BaseBackActivity.TYPE_NO_CONTENT, false)
                                closeStateView()
                            }
                        } else {
                            showStateView(BaseBackActivity.TYPE_NET_NOT_GIVE_FORCE, false)
                            closeStateView()
                        }
                    }
                    getReviewList()
                }

                override fun onError(e: Throwable) {
//                      if (ivHeadImg.visibility != View.VISIBLE)
//                         showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
//                    else
//                    closeStateView()
                }

                override fun onComplete() {
                }
            })
    }

    private fun getReviewList() {

        SpiderCmsApi.getSpiderCmsApiJson(context)
            .getMagazineReviewList(
                if (!TextUtils.isEmpty(magazineId)) magazineId!!.toLong() else 0L,
                year
            )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: JSONObject) {

                    t.let {
                        val state = it.optInt("state")
                        if (state == 200) {
                            val data = it.optJSONArray("data")
                            val taskList = FAST.parseArray(
                                data.toString(),
                                MagazineReviewBean::class.java
                            ) as ArrayList
                            if (taskList.size > 0) {

                                adapter?.setNewData(taskList)
                                closeStateView()

                            } else {
                                showStateView(BaseBackActivity.TYPE_NO_CONTENT, false)
                                closeStateView()
                            }
                        } else {
                            showStateView(BaseBackActivity.TYPE_NET_NOT_GIVE_FORCE, false)
                            closeStateView()
                        }
                    }
                }

                override fun onError(e: Throwable) {
//                      if (ivHeadImg.visibility != View.VISIBLE)
//                         showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
//                    else
                    closeStateView()
                }

                override fun onComplete() {
                }
            })
    }

    val bottomSheetDialog: BottomSheetDialog by lazy {
        BottomSheetDialog(requireContext())
    }

    private fun allReviewDialog() {
        context?.let {

            val view = LayoutInflater.from(it).inflate(R.layout.dialog_review_layout, null)

            val layoutManager = GridLayoutManager(it, 4)
            view.reviewList.layoutManager = layoutManager
            val adapter = MagazineReviewTopAdapter(context, allList)
            view.reviewList.adapter = adapter
            adapter.setCheckItemClickListener { position ->
                year = allList[position]
                getReviewList()
                bottomSheetDialog.dismiss()
                if ((position % 4 == 0)) {//取当前点击的年份和后面三个数据重新给topAdapter设置数据
                    topList.clear()
                    var lastPosition = position
                    if (position + 3 < allList.size) {
                        lastPosition += 3
                    } else if (position + 2 < allList.size) {
                        lastPosition += 2
                    } else if (position + 1 < allList.size) {
                        lastPosition += 1
                    }
                    for (i in position..lastPosition) {
                        topList.add(allList[i])
                    }
                } else if ((position % 4 == 1)) {
                    topList.clear()

                    var lastPosition = position
                    if (position + 2 < allList.size) {
                        lastPosition += 2
                    } else if (position + 1 < allList.size) {
                        lastPosition += 1
                    }
                    for (i in position - 1..lastPosition) {
                        topList.add(allList[i])
                    }
                } else if ((position % 4 == 2)) {
                    topList.clear()
                    var lastPosition = position
                    if (position + 1 < allList.size) {
                        lastPosition += 1
                    }
                    for (i in position - 2..lastPosition) {
                        topList.add(allList[i])
                    }
                } else {
                    topList.clear()
                    for (i in position - 3..position) {
                        topList.add(allList[i])
                    }
                }
                topAdapter?.notifyDataSetChanged()
            }
            for (i in 0..allList.size) {
                if (year == allList[i]) {
                    adapter.setCurrPosition(i)
                    break
                }
            }
            bottomSheetDialog.setOnDismissListener {

                for (i in 0..topList.size) {
                    if (year == topList[i]) {
                        topAdapter?.setCurrPosition(i)
                        break
                    }
                }

            }
            view.close.setOnClickListener {
                bottomSheetDialog.dismiss()
            }
            bottomSheetDialog.setContentView(view)
            bottomSheetDialog.setCancelable(false)
            bottomSheetDialog.setCanceledOnTouchOutside(true)
            bottomSheetDialog.show()

        }
    }

}